package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AuthCodeRepository;
import com.lagou.edu.entity.AuthCode;
import com.lagou.edu.service.code.CodeService;
import com.lagou.edu.service.mail.MailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.transaction.Transactional;
import java.util.Date;

@Slf4j
@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private AuthCodeRepository authCodeRepository;

    @Reference
    private MailService mailService;

    @Transactional
    public boolean create(String email){
        try {
            String randomNumeric = RandomStringUtils.randomNumeric(6);
            Date now = new Date();
            Date tenMinutes = DateUtils.addMinutes(now, 1);
            authCodeRepository.save(AuthCode.builder()
                    .email(email)
                    .code(randomNumeric)
                    .createtime(now)
                    .expiretime(tenMinutes)
                    .build());
            mailService.sendMail(email,randomNumeric);
        }catch (Exception e){
            log.error("error",e);
            return false;
        }
        return true;
    }

    public int validate(String email, String code){
        AuthCode authCode = authCodeRepository.findTopByEmailOrderByCreatetimeDesc(email);
        if (authCode != null && StringUtils.equals(authCode.getCode(),code)){
            if (authCode.getExpiretime().after(new Date())){
                return 0;
            }else {
                return 2;
            }
        }
        return 1;
    }

}
